package cn.endeavour.user.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 登录拦截器,没有登录不放行
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("====================");
        String token = request.getHeader("token");
        // 判断是否为null
        if (!StringUtils.isEmpty(token)) {
            // 查询Redis中的数据
            Object obj = redisTemplate.opsForValue().get(token);
            if (obj != null) {
                // 重新保存
                redisTemplate.opsForValue().set(token, obj, 30, TimeUnit.MINUTES);
                // 放行
                return true;
            }
        }
        // 返回数据给前端
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("{\"success\":false,msg:\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;
    }
}
